<template>
    <van-form @submit="onSubmit">
        <van-cell-group inset>
            <van-field
                :name="editUser.editName"
                :label="editUser.editName"
                v-if="editUser.editKey === 'gender'"
            >
                <template #input>
                    <van-radio-group v-model="editUser.currentValue" direction="horizontal">
                        <van-radio name="0">男</van-radio>
                        <van-radio name="1">女</van-radio>
                    </van-radio-group>
                </template>
            </van-field>
            <van-field
                v-model="editUser.currentValue"
                :name="editUser.editName"
                :label="editUser.editName"
                :placeholder="`请输入${editUser.editName}`"
                :rules="[{ required: true, message: '请输入${editUser.editName}`' }]"
                v-else
            />
        </van-cell-group>
        <div style="margin: 16px">
            <van-button round block type="primary" native-type="submit"> 提交 </van-button>
        </div>
    </van-form>
</template>

<script setup lang="ts">
import { useRoute } from 'vue-router'
import { ref } from 'vue'
import myAxios from '../plugins/myAxios.ts'
import { showFailToast, showSuccessToast } from 'vant'
import router from "../router";
import { getCurrentUser } from '../services/user.ts'

const route = useRoute()

const getQueryParam = (param: unknown): string | undefined => {
    if (Array.isArray(param)) return param[0]
    if (typeof param === 'string') return param
    return undefined
}

const editUser = ref({
    editKey: getQueryParam(route.query.editKey),
    editName: getQueryParam(route.query.editName),
    currentValue: getQueryParam(route.query.currentValue)
})

const onSubmit = async () => {
    const currentUser = await getCurrentUser();

    if (!currentUser) {
        showFailToast('用户未登录');
    }
    const res = await myAxios
        .post('/user/update', {
            id: currentUser.id,
            [editUser.value.editKey as string]: editUser.value.currentValue
        })
    if (res['code'] === 0 && res.data > 0) {
        showSuccessToast("修改成功")
        router.back();
    } else {
        showFailToast("修改失败")
    }
}
</script>

<style scoped></style>
